package com.yixun.qfbao.service.impl;

import com.yixun.qfbao.enums.FileTypeEnum;
import com.yixun.qfbao.exception.YXUNCheckedException;
import com.yixun.qfbao.exception.enums.ExceptionCodeEnum;
import com.yixun.qfbao.service.CommonService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Calendar;

@Service("commonService")
public class CommonServiceImpl implements CommonService {
	private static Logger log = Logger.getLogger(CommonServiceImpl.class);
	@Value("#{configProperties['image.savePath']}")
	public String  savePath;
	@Value("#{configProperties['image.requestPath']}")
	public String  requestPath;
	@Value("#{configProperties['wxFile.savePath']}")
	public String  wxConfigSavePath;
	@Value("#{configProperties['wxFile.requestPath']}")
	public String  WxConfigRequestPath;

	/**
	 * 保存文件
	 * @param file
	 * @return
	 */
	@Override
	public String saveFile(MultipartFile file, FileTypeEnum type, String sourceFileName){
		if(file == null || file.isEmpty()){
			throw new YXUNCheckedException(ExceptionCodeEnum.FILE_NO_EXIST.getCode());
		}
		
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String dateStr = format.format(Calendar.getInstance().getTime());
		String fileName  = String.valueOf(Calendar.getInstance().getTime().getTime());
		String imageName = "";
		if(!StringUtils.isNotEmpty(sourceFileName)){
//			imageName = UUID.randomUUID().toString()+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
			imageName = fileName+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
		}else{
			imageName = sourceFileName;
		}
		String path = type.getPath()+"/"+dateStr+"/"+imageName;
		//savePath = "F:/yixun_pro/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp7/wtpwebapps/ROOT/upload";
		File newFile = new File(savePath+(savePath.endsWith("/")?"":"/")+path);
		if (!newFile.getParentFile().exists()) {
			if(!newFile.getParentFile().mkdirs()){
				throw new YXUNCheckedException(ExceptionCodeEnum.IMG_PATH_ERROR.getCode());
			}
		}
		try {
			file.transferTo(newFile);
			isPng(newFile,type,fileName,FilenameUtils.getExtension(file.getOriginalFilename()),dateStr);
		} catch (Exception e) {
			log.error("file upload error: {}", e);
			throw new YXUNCheckedException(ExceptionCodeEnum.SAVE_IMG_FAIL.getCode(),e);
		}
		//requestPath = "http://127.0.0.1:8888/upload";
		return requestPath+(requestPath.endsWith("/")?"":"/")+path;
	}

	/**
	 * 保存微信配置文件
	 * @method: saveWxFile
	 * @param: [file, typeEn, sourceFileName]
	 * @return: java.lang.String
	 */
	@Override
	public String saveWxFile(MultipartFile file) {
		String path;
		if(file == null || file.isEmpty()){
			throw new YXUNCheckedException(ExceptionCodeEnum.FILE_NO_EXIST.getCode());
		}

		String filename = file.getOriginalFilename();
		String fileType = filename.substring(filename.length() - 4);
		path = wxConfigSavePath + filename.substring(0, filename.length() - 4) + fileType;

		File newFile = new File(path);
		if (!newFile.exists()) {
			newFile.mkdirs();
		}
		if (file.getSize() > 50 * 1024) {
			throw new YXUNCheckedException(ExceptionCodeEnum.File_SIZE_ERROR.getCode());
		}
		try {
			file.transferTo(newFile);
		} catch (Exception e) {
			log.error("wxConfigFile upload error: {}", e);
			throw new YXUNCheckedException(ExceptionCodeEnum.SAVE_IMG_FAIL.getCode(),e);
		}
		return wxConfigSavePath;
	}


	//生成中等 小型两张图片
	private void isPng(File newFile,FileTypeEnum type,String fileName,String fileType,String fileDir){
		//中等压缩，最小压缩
		String midFile = savePath+(savePath.endsWith("/")?"":"/")+type.getPath()+"/"+fileDir+"/"+fileName + "-m." + fileType;
		String smallFile = savePath+(savePath.endsWith("/")?"":"/")+type.getPath()+"/"+fileDir+"/"+fileName + "-s." + fileType;
		try {
			Thumbnails.Builder<File> fileBuilder = Thumbnails.of(newFile).scale(1.0).outputQuality(1.0);
			BufferedImage originalImage = fileBuilder.asBufferedImage();
			if("png".equals(fileType)){
				if(originalImage.getWidth() > 1200){
					//中等压缩
					Thumbnails.of(newFile).width(800).outputQuality(1f).toFile(midFile);
				}else{
					copyFile(newFile,midFile);
				}
				if(originalImage.getWidth() > 800){
					//最小压缩
					Thumbnails.of(newFile).width(400).outputQuality(1f).toFile(smallFile);
				}else{
					copyFile(newFile,smallFile);
				}

			}else{
				if(originalImage.getWidth() > 1200){
					//中等压缩
					Thumbnails.of(newFile).scale(0.5).outputQuality(0.5f).toFile(midFile);
				}else{
					copyFile(newFile,midFile);
				}
				if(originalImage.getWidth() > 800){
					//最小压缩
					Thumbnails.of(newFile).scale(0.3).outputQuality(0.3f).toFile(smallFile);
				}else{
					copyFile(newFile,smallFile);
				}


			}
		}catch (Exception e){
			log.error(e.getMessage());
		}
	}

	/**
	 * 复制文件
	 */
	private void copyFile(File file,String newFilePath){
		FileChannel input = null;
		FileChannel output = null;

		try {
			input = new FileInputStream(file).getChannel();
			output = new FileOutputStream(newFilePath).getChannel();
			output.transferFrom(input, 0, input.size());
		} catch (Exception e) {
			log.error("copyFile error: {}",e);
		} finally {
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				log.error("copyFile error: {}", e);
			}
		}

	}
}
